package com.yixun.qfbao.hander;

import com.yixun.qfbao.api.service.CPReportService;
import com.yixun.qfbao.apidto.UpdateSaleStatusReqDto;
import com.yixun.qfbao.apidto.UpdateSaleStatusResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.vo.UpdateSaleStatusReqVo;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NewUpdateSaleStatusHander extends CommonAbstractHander {

    private static final Logger logger = LoggerFactory.getLogger(NewUpdateSaleStatusHander.class);

    @Autowired
    private CPReportService cpReportService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

    @Override
    public BaseResponseDTO doBusiness(BaseRequestDTO baseRequestDTO) {
        UpdateSaleStatusReqVo reqVo = (UpdateSaleStatusReqVo) baseRequestDTO;
        UpdateSaleStatusReqDto reqDto =  reqVo.getParams();
        BaseResponseDTO<UpdateSaleStatusResDto> res = new BaseResponseDTO<>();
        UpdateSaleStatusResDto resDto = new UpdateSaleStatusResDto();
        try {
            if(StringUtils.isBlank(reqDto.getRecommendedChannelId())) {
                throw new TServerException("报备ID不能为空！");
            }
            // 通过报备ID获取公司信息
            CustomerPremisesDto cp = customerPremisesService.selectCompanyByCpId(Long.valueOf(reqDto.getRecommendedChannelId()));
            //获取分销助手和案场助手的微信accessToken
            String agencyAccessToken = wxAccessTokenCacheUtils.getAccessToken(cp.getCompanyUuid(), SystemIdEnum.AGENCY_h5.getCode(), null);
            String assistantAccessToken = wxAccessTokenCacheUtils.getAccessToken(cp.getCompanyUuid(), SystemIdEnum.ASSISTANT.getCode(), null);
            resDto = cpReportService.newUpdateSaleStatusHander(reqDto, cp, agencyAccessToken, assistantAccessToken);
        } catch (TServerException te) {
          logger.error("UpdateSaleStatusHander bus error: {}", te);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg(te.getErrorMsg());
        } catch (Exception e) {
            logger.error("UpdateSaleStatusHander error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("更新状态失败！");
        }
        res.setResult(resDto.getResult());
        res.setResData(resDto);
        return res;
    }
}
